﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using Tesla.Core;
using Tesla.Graphics.Implementation;

namespace Tesla.Graphics {
    /// <summary>
    /// DepthStencilState object that controls the depth-stencil buffer.
    /// </summary>
    public class DepthStencilState : RenderState {
        private DepthStencilStateImplementation _impl;
        private RenderStateKey _key;

        /// <summary>
        /// Gets a built-in state object where the depth buffer is disabled and writing is disabled.
        /// </summary>
        public static DepthStencilState None {
            get;
            internal set;
        }

        /// <summary>
        /// Gets a built-in state object where the depth buffer is enabled and writing to the depth buffer is disabled.
        /// </summary>
        public static DepthStencilState DepthWriteOff {
            get;
            internal set;
        }

        /// <summary>
        /// Gets a built-in state object where the depth buffer is enabld and writing to it is enabled.
        /// This is the default state.
        /// </summary>
        public static DepthStencilState Default {
            get;
            internal set;
        }

        /// <summary>
        /// Get if this render state has been bound to the pipeline.
        /// </summary>
        public override bool IsBound {
            get {
                return _impl.IsBound;
            }
        }

        /// <summary>
        /// Gets the <see cref="RenderStateKey"/> that is used to compare this state
        /// to another state.
        /// </summary>
        public override RenderStateKey RenderStateKey {
            get {
                if(!_impl.IsBound) {
                    return new RenderStateKey(GetHashCode(), StateType);
                }
                return _key;
            }
        }


        /// <summary>
        /// Get the enumeration describing this render state.
        /// </summary>
        public override RenderStateType StateType {
            get {
                return RenderStateType.DepthStencilState;
            }
        }

        /// <summary>
        /// Gets the API-specific implementation of this resource.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets or sets if the depth buffer should be enabled. The default value is true.
        /// </summary>
        public bool DepthEnable {
            get {
                return _impl.DepthEnable;
            }
            set {
                _impl.DepthEnable = value;
            }
        }

        /// <summary>
        /// Gets or sets if the depth buffer should be writable. The default value is true.
        /// </summary>
        public bool DepthWriteEnable {
            get {
                return _impl.DepthWriteEnable;
            }
            set {
                _impl.DepthWriteEnable = value;
            }
        }

        /// <summary>
        /// Gets or sets the depth comparison function for the depth test. The default value
        /// is <see cref="ComparisonFunction.LessEqual"/>.
        /// </summary>
        public ComparisonFunction DepthFunction {
            get {
                return _impl.DepthFunction;
            }
            set {
                _impl.DepthFunction = value;
            }
        }

        /// <summary>
        /// Gets or sets if the stencil buffer should be enabled. The default value is false.
        /// </summary>
        public bool StencilEnable {
            get {
                return _impl.StencilEnable;
            }
            set {
                _impl.StencilEnable = value;
            }
        }

        /// <summary>
        /// Gets or sets the reference stencil value used for stencil testing. The default valut
        /// is zero.
        /// </summary>
        public int ReferenceStencil {
            get {
                return _impl.ReferenceStencil;
            }
            set {
                _impl.ReferenceStencil = value;
            }
        }

        /// <summary>
        /// Gets or sets the comparison function used for testing a counterclockwise triangle. The
        /// default value is <see cref="ComparisonFunction.Always"/>.
        /// </summary>
        public ComparisonFunction CounterClockwiseStencilFunction {
            get {
                return _impl.CounterClockwiseStencilFunction;
            }
            set {
                _impl.CounterClockwiseStencilFunction = value;
            }
        }

        /// <summary>
        /// Gets or sets the stencil operation done when the stencil test passes, but the depth test fails
        /// for a counterclockwise triangle. The default value is <see cref="StencilOperation.Keep"/>.
        /// </summary>
        public StencilOperation CounterClockwiseStencilDepthFail {
            get {
                return _impl.CounterClockwiseStencilDepthFail;
            }
            set {
                _impl.CounterClockwiseStencilDepthFail = value;
            }
        }

        /// <summary>
        /// Gets or sets the stencil operation done when the stencil test fails for
        /// a counterclockwise triangle. The default value is <see cref="StencilOperation.Keep"/>.
        /// </summary>
        public StencilOperation CounterClockwiseStencilFail {
            get {
                return _impl.CounterClockwiseStencilFail;
            }
            set {
                _impl.CounterClockwiseStencilFail = value;
            }
        }

        /// <summary>
        /// Gets or sets the stencil operation done when the stencil test passes for
        /// a counterclockwise triangle. The default value is <see cref="StencilOperation.Keep"/>.
        /// </summary>
        public StencilOperation CounterClockwiseStencilPass {
            get {
                return _impl.CounterClockwiseStencilPass;
            }
            set {
                _impl.CounterClockwiseStencilPass = value;
            }
        }

        /// <summary>
        /// Gets or sets the comparison function used for testing a clockwise triangle. The
        /// default value is <see cref="ComparisonFunction.Always"/>.
        /// </summary>
        public ComparisonFunction StencilFunction {
            get {
                return _impl.StencilFunction;
            }
            set {
                _impl.StencilFunction = value;
            }
        }

        /// <summary>
        /// Gets or sets the stencil operation done when the stencil test passes but
        /// the depth test fails for a clockwise triangle. The default value is <see cref="StencilOperation.Keep"/>.
        /// </summary>
        public StencilOperation StencilDepthFail {
            get {
                return _impl.StencilDepthFail;
            }
            set {
                _impl.StencilDepthFail = value;
            }
        }

        /// <summary>
        /// Gets or sets the stencil operation done when the stencil test fails
        /// for a clockwise triangle. The default value is <see cref="StencilOperation.Keep"/>.
        /// </summary>
        public StencilOperation StencilFail {
            get {
                return _impl.StencilFail;
            }
            set {
                _impl.StencilFail = value;
            }
        }

        /// <summary>
        /// Gets or sets the stencil operation done when the stencil test passes
        /// for a clockwise triangle. The default value is <see cref="StencilOperation.Keep"/>.
        /// </summary>
        public StencilOperation StencilPass {
            get {
                return _impl.StencilPass;
            }
            set {
                _impl.StencilPass = value;
            }
        }

        /// <summary>
        /// Gets or sets if two sided stenciling should be enabled, that is if counterclockwise
        /// stencil testing/operations should be conducted. The default value is false.
        /// </summary>
        public bool TwoSidedStencilEnable {
            get {
                return _impl.TwoSidedStencilEnable;
            }
            set {
                _impl.TwoSidedStencilEnable = value;
            }
        }

        /// <summary>
        /// Gets or sets the value that identifies a portion of the depth-stencil buffer for reading stencil data.
        /// The default value is <see cref="int.MaxValue"/>.
        /// </summary>
        public int StencilReadMask {
            get {
                return _impl.StencilReadMask;
            }
            set {
                _impl.StencilReadMask = value;
            }
        }

        /// <summary>
        /// Gets or sets the value that identifies a portion of the depth-stencil buffer for writing stencil data.
        /// The default value is <see cref="int.MaxValue"/>.
        /// </summary>
        public int StencilWriteMask {
            get {
                return _impl.StencilWriteMask;
            }
            set {
                _impl.StencilWriteMask = value;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="DepthStencilState"/> with default values.
        /// </summary>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public DepthStencilState() {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateDepthStencilStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            SetDefaults();
        }

        /// <summary>
        /// Creates a new instance of <see cref="DepthStencilState"/> with default values.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public DepthStencilState(IRenderSystemProvider renderSystem) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateDepthStencilStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            SetDefaults();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="DepthStencilState"/> is reclaimed by garbage collection.
        /// </summary>
        ~DepthStencilState() {
            Dispose(false);
        }

        private void SetDefaults() {
            //Set defaults
            _impl.DepthEnable = true;
            _impl.DepthWriteEnable = true;
            _impl.DepthFunction = ComparisonFunction.LessEqual;
            _impl.StencilEnable = false;
            _impl.ReferenceStencil = 0;
            _impl.CounterClockwiseStencilFunction = ComparisonFunction.Always;
            _impl.CounterClockwiseStencilDepthFail = StencilOperation.Keep;
            _impl.CounterClockwiseStencilFail = StencilOperation.Keep;
            _impl.CounterClockwiseStencilPass = StencilOperation.Keep;
            _impl.StencilFunction = ComparisonFunction.Always;
            _impl.StencilDepthFail = StencilOperation.Keep;
            _impl.StencilFail = StencilOperation.Keep;
            _impl.StencilPass = StencilOperation.Keep;
            _impl.TwoSidedStencilEnable = false;
            _impl.StencilReadMask = int.MaxValue;
            _impl.StencilWriteMask = int.MaxValue;
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>A hash code for this instance.</returns>
        public override int GetHashCode() {
            int hash = StateType.GetHashCode();
            hash = ((hash << 2) - hash) + ((_impl.DepthEnable) ? 1 : 0);
            hash = ((hash << 2) - hash) + ((_impl.DepthWriteEnable) ? 1 : 0);
            hash = ((hash << 2) - hash) + _impl.DepthFunction.GetHashCode();
            hash = ((hash << 2) - hash) + ((_impl.StencilEnable) ? 1 : 0);
            hash = ((hash << 2) - hash) + ((_impl.TwoSidedStencilEnable) ? 1 : 0);
            hash = ((hash << 2) - hash) + _impl.ReferenceStencil;
            hash = ((hash << 2) - hash) + _impl.StencilFunction.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.StencilDepthFail.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.StencilFail.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.StencilPass.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.CounterClockwiseStencilFunction.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.CounterClockwiseStencilDepthFail.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.CounterClockwiseStencilFail.GetHashCode();
            hash = ((hash << 2) - hash) + _impl.CounterClockwiseStencilPass.GetHashCode();
            hash = ((hash << 2) - hash) + (_impl.StencilWriteMask % int.MaxValue);
            hash = ((hash << 2) - hash) + (_impl.StencilReadMask % int.MaxValue);
            return hash;
        }

        /// <summary>
        /// Binds the render state to the graphics pipeline. This is automatically called the first time the
        /// renderstate is applied or manually called to create the underlying implementation early.
        /// </summary>
        public override void BindRenderState() {
            if(!IsBound) {
                _impl.BindDepthStencilState();
                _key = new RenderStateKey(GetHashCode(), StateType);
            }
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public override void Write(Content.ISavableWriter output) {
            output.Write("DepthEnable", _impl.DepthEnable);
            output.Write("DepthWriteEnable", _impl.DepthWriteEnable);
            output.WriteEnum<ComparisonFunction>("DepthFunction", _impl.DepthFunction);
            output.Write("StencilEnable", _impl.StencilEnable);
            output.Write("ReferenceStencil", _impl.ReferenceStencil);
            output.WriteEnum<ComparisonFunction>("CounterClockwiseStencilFunction", _impl.CounterClockwiseStencilFunction);
            output.WriteEnum<StencilOperation>("CounterClockwiseStencilDepthFail", _impl.CounterClockwiseStencilDepthFail);
            output.WriteEnum<StencilOperation>("CounterClockwiseStencilFail", _impl.CounterClockwiseStencilFail);
            output.WriteEnum<StencilOperation>("CounterClockwiseStencilPass", _impl.CounterClockwiseStencilPass);
            output.WriteEnum<ComparisonFunction>("StencilFunction", _impl.StencilFunction);
            output.WriteEnum<StencilOperation>("StencilDepthFail", _impl.StencilDepthFail);
            output.WriteEnum<StencilOperation>("StencilFail", _impl.StencilFail);
            output.WriteEnum<StencilOperation>("StencilPass", _impl.StencilPass);
            output.Write("TwoSidedStencilEnable", _impl.TwoSidedStencilEnable);
            output.Write("StencilReadMask", _impl.StencilReadMask);
            output.Write("StencilWriteMask", _impl.StencilWriteMask);
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails or the render
        /// system is not set.</exception>
        public override void Read(Content.ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;
            try {
                _impl = renderSystem.CreateDepthStencilStateImplementation();
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }

            _impl.DepthEnable = input.ReadBoolean();
            _impl.DepthWriteEnable = input.ReadBoolean();
            _impl.DepthFunction = input.ReadEnum<ComparisonFunction>();
            _impl.StencilEnable = input.ReadBoolean();
            _impl.ReferenceStencil = input.ReadInt();
            _impl.CounterClockwiseStencilFunction = input.ReadEnum<ComparisonFunction>();
            _impl.CounterClockwiseStencilDepthFail = input.ReadEnum<StencilOperation>();
            _impl.CounterClockwiseStencilFail = input.ReadEnum<StencilOperation>();
            _impl.CounterClockwiseStencilPass = input.ReadEnum<StencilOperation>();
            _impl.StencilFunction = input.ReadEnum<ComparisonFunction>();
            _impl.StencilDepthFail = input.ReadEnum<StencilOperation>();
            _impl.StencilFail = input.ReadEnum<StencilOperation>();
            _impl.StencilPass = input.ReadEnum<StencilOperation>();
            _impl.TwoSidedStencilEnable = input.ReadBoolean();
            _impl.StencilReadMask = input.ReadInt();
            _impl.StencilWriteMask = input.ReadInt();

            this.BindRenderState();
        }
    }
}
